package com.mega.center.auth.controller;

import com.mega.center.auth.model.dto.LoginDTO;
import com.mega.center.auth.service.LoginService;
import com.mega.common.core.domain.R;
import com.mega.common.core.utils.StringUtils;
import com.mega.common.log.annotation.SysLog;
import com.mega.common.log.enums.BusinessType;
import com.mega.common.security.service.TokenService;
import com.mega.system.api.vo.LoginUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * token 控制
 *
 * @author mega
 */
@Slf4j
@RestController
@RequestMapping("/auth")
@ApiModel(value = "用户认证", description = "用户认证")
@Api(tags = "用户认证")
public class TokenController {

    @Autowired
    private TokenService tokenService;
    @Autowired
    private LoginService loginService;

    /**
     * 登录
     *
     * @param dto
     * @return
     */
    @PostMapping("login")
    @ApiOperation(value = "登录")
    @SysLog(title = "登录", businessType = BusinessType.LOGIN)
    public R login(@RequestBody LoginDTO dto) {
        // 用户登录
        LoginUser userInfo = loginService.login(dto.getUsername(), dto.getPassword());
        // 获取登录token
        return R.ok(tokenService.createToken(userInfo));
    }

    /**
     * 退出
     *
     * @param request
     * @return
     */
    @DeleteMapping("logout")
    @ApiOperation(value = "退出")
    @SysLog(title = "退出", businessType = BusinessType.LOGINOUT)
    public R<?> logout(HttpServletRequest request) {
        LoginUser loginUserVO = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUserVO)) {
            // 删除用户缓存记录
            tokenService.delLoginUser(loginUserVO.getToken());
        }
        return R.ok();
    }

    /**
     * 刷新token
     *
     * @param request
     * @return
     */
    @PostMapping("refresh")
    @ApiOperation(value = "刷新token")
    @SysLog(title = "刷新token", businessType = BusinessType.REFRESH)
    public R<?> refresh(HttpServletRequest request) {
        LoginUser loginUserVO = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUserVO)) {
            // 刷新令牌有效期
            return R.ok(tokenService.refreshToken(loginUserVO));
        }
        return R.ok();
    }
}
